﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace LLoger
{
    public class FileLogWriter : ILogWriter
    {
        private readonly string _fileName;
        private int _currSize = 0;
        private StreamWriter _streamWriter;


        public FileLogWriter(string fileName, int maxSize)
        {
            _fileName = CheckFolderAndFile(fileName);

            _streamWriter = new StreamWriter(_fileName, true, Encoding.UTF8);
            WriteLine("=============================== Log Session Started ===============================");
        }

        private string CheckFolderAndFile(string fileName)
        {
            string asmName = "Events";

            try
            {
                asmName = Assembly.GetEntryAssembly().GetName().Name;
            }
            catch{}

            fileName = string.IsNullOrEmpty(fileName) ? asmName + ".log" : fileName;
            var filePath = Path.GetDirectoryName(fileName);

            if (!string.IsNullOrEmpty(filePath) && !Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            return fileName;
        }

        public virtual void WriteLine(string val)
        {
            lock (_streamWriter)
            {
                _streamWriter.WriteLine(DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss\t") + val);
                _streamWriter.Flush();
            }
        }

        public void WriteLine(string val, params object[] args)
        {
            WriteLine(string.Format(val, args));
        }

        public void WriteLine(Exception ex, string extMsg)
        {
            extMsg = string.IsNullOrEmpty(extMsg) ? "" : extMsg + ": ";
            WriteLine(extMsg + ex.Message + Environment.NewLine + ex.StackTrace);

        }

        public void WriteLine(Exception ex)
        {
            WriteLine(ex, "");
        }

        public void Dispose()
        {
            if (_streamWriter != null)
            {
                _streamWriter.Dispose();
            }
        }
    }
}
